package cn.edu.zafu.camera;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tms.app.tms.R;
import com.tms.app.tms.adapter.BdAdapter;
import com.tms.app.tms.app.MyApp;
import com.tms.app.tms.ui.base.ui.BaseActivity;
import com.tms.app.tms.ui.base.ui.BaseActivity;
import com.tms.app.tms.utils.ImageUtil;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.edu.zafu.camera.activity.CameraActivity;


/**
 * User:lizhangqu(513163535@qq.com)
 * Date:2015-09-05
 * Time: 13:49
 */
public class CameraBaiDuActivity extends BaseActivity {
    @BindView(R.id.edit_xh)
    EditText editXh;
    @BindView(R.id.text_info)
    TextView textInfo;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private final String imgBasePath = "/sdcard/tms/bdorc/img/";
    @BindView(R.id.img)
    ImageView imageView;
    @BindView(R.id.radio)
    RadioGroup radio;
    @BindView(R.id.edit_xh_head)
    EditText editXhHead;
    @BindView(R.id.recognize_head)
    Button recognizeHead;
    @BindView(R.id.button_save)
    Button buttonSave;
    @BindView(R.id.textView3)
    TextView textView3;
    private String mPhotoPath = "";
    private static final int UPDATE_TEXTVIEW = 1;
    private static final String token = "24.a30889cb6f6b7ada09a4d46401ca7e86.2592000.1513314172.282335-10364995";
    private DbManager db;
    private OrcText orcText;
    private String resultDb;
    private int resultCode;
    private BdAdapter bdAdapter;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 222:
                    showOrcResult();
                    break;
                case -1:
                    editXh.setText("");
                    Toast.makeText(getApplicationContext(), "识别失败", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };
    private boolean isSave = true;
    private String afterBase64;
    private int orcType = 2;
    private String orcPrefixChar;
    private String rightRrefixChar;


    private void saveOrcResult() {
        orcText = new OrcText();
        orcText.setUrl(mPhotoPath);
        orcText.setResultCode(resultCode);
        orcText.setResultBd(resultDb);
        orcText.setAfterBase64(afterBase64);
        orcText.setResuletCusm(editXh.getText().toString());
        saveFileToDb(orcText);


        isSave = true;
        List<OrcText> list = getFileFromDb();
        int failnum = getFialNumFromDb();
        textInfo.setText("统计结果：总识别次数:" + list.size() + ",失败次数:" + failnum);
        bdAdapter.getData().clear();
        bdAdapter.getData().addAll(list);
        bdAdapter.notifyDataSetChanged();
        editXh.setText("");
        imageView.setVisibility(View.INVISIBLE);
        editXh.setText("");
        recognizeHead.setEnabled(false);


    }


    private void showOrcResult() {
        if (resultDb==null)
            resultDb="";
        String text=OrcTextUtil.getGussOrcText(resultDb);
        if (OrcTextUtil.getGussOrcText(resultDb)!=null)
            editXh.setText(OrcTextUtil.getGussOrcText(resultDb));
        else
            editXh.setText(resultDb);
        if (resultCode == 1) {
            editXh.setTextColor(getResources().getColor(R.color.color_font_black));
        } else {
            editXh.setTextColor(getResources().getColor(R.color.red));
        }
        String headText=HeadCharUtil.getHeadCharByText(text);
        boolean flag=HeadCharUtil.checkHeadChar(headText);
        if (OrcTextUtil.checkTextRight(text)&&!flag){
            editXhHead.setText(HeadCharUtil.getHeadCharByText(text));
            recognizeHead.setEnabled(true);
        }else {
            editXhHead.setText("");
            recognizeHead.setEnabled(false);
        }


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_bd);
        ButterKnife.bind(this);
        try {
            db = x.getDb(MyApp.getDaoConfig());
        } catch (Exception e) {
            e.printStackTrace();
        }
        bdAdapter = new BdAdapter();
        LinearLayoutManager mgr = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mgr);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(bdAdapter);
        radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == R.id.button_1)
                    orcType = 1;
                else
                    orcType = 2;
            }
        });

        editXhHead.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length()>=4){
                   // editXhHead.setText(s.toString().toUpperCase());
                    recognizeHead.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    @Override
    protected void onStart() {
        super.onStart();
        try {
            db = x.getDb(MyApp.getDaoConfig());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.button_save, R.id.recognize,R.id.recognize_head})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_save:
                if (isSave) {
                    Toast.makeText(this, "请先拍照", Toast.LENGTH_SHORT).show();
                    return;
                }
                saveOrcResult();

                break;
            case R.id.recognize_head:
                String header=editXhHead.getText().toString().replace(" ","").toUpperCase();
                if (header!=null&&header.length()>0){
                    header=header.substring(0,4);
                    HeadCharUtil.saveHeadCharHeadChar(header);
                    editXhHead.setText("");
                    recognizeHead.setEnabled(false);
                    showMsg("更新成功");
                }else {
                    showMsg("头部字典数据格式不对");
                }

            break;
            case R.id.recognize:
                if (!isSave) {
                    Toast.makeText(this, "请先保存本次识别结果", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<OrcText> list = getFileFromDb();
                if (list != null && list.size() >= 49) {
                    Toast.makeText(this, "您免费次数已经用完请充值", Toast.LENGTH_SHORT).show();
                    return;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//小写的mm表示的是分钟
                Intent intent = new Intent(CameraBaiDuActivity.this, CameraActivity.class);
                intent.putExtra("path", imgBasePath);
                intent.putExtra("name", sdf.format(new Date()) + ".jpg");
                intent.putExtra("type", "idcardFront");
                startActivityForResult(intent, 100);
                break;
        }
    }

    private void uploadAndRecognize() {
        orcText = new OrcText();
        orcText.setUrl(mPhotoPath);
        RequestParams params = null;
        if (orcType == 1)
            params = new RequestParams("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic");
        else

            params = new RequestParams("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic");

        params.addHeader("Content-Type", "application/x-www-form-urlencoded");
        params.setMultipart(true);
        params.addBodyParameter("access_token", token);
        afterBase64 = ImageUtil.bitmapToString(mPhotoPath);
        params.addBodyParameter("image", afterBase64);
        params.addBodyParameter("detect_direction", "true");
        params.addBodyParameter("language_type", "ENG");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
                BdJson json = gson.fromJson(result, BdJson.class);
                if (json == null) {
                    handler.sendEmptyMessage(-1);
                    resultCode = 0;
                    resultDb = result;
                    return;
                }
                if (json.getWords_result() == null || json.getWords_result().size() < 1) {
                    handler.sendEmptyMessage(-1);
                    resultCode = 0;
                    resultDb = result;
                    return;
                }
                resultDb = json.getWords_result().get(0).getWords();
                resultDb = OrcTextUtil.formatOrcText(resultDb);
                if (OrcTextUtil.checkTextRight(resultDb))
                    resultCode = 1;
                else
                    resultCode = 0;
                handler.sendEmptyMessage(222);


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                handler.sendEmptyMessage(-1);
                resultCode = 0;
                resultDb = ex.getMessage();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {


            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("TAG", "onActivityResult");
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                Bundle extras = data.getExtras();
                String path = extras.getString("path");
                String type = extras.getString("type");
                //   Toast.makeText(getApplicationContext(), "path:" + path + " type:" + type, Toast.LENGTH_LONG).show();
                mPhotoPath = path;
                uploadAndRecognize();
                Glide.with(imageView.getContext()).load(new File(path)).error(R.mipmap.ic_launcher).into(imageView);
                imageView.setVisibility(View.VISIBLE);
                isSave = false;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void saveFileToDb(OrcText orcText) {
        try {
            if (db == null)
                return;
            db.saveOrUpdate(orcText);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private List<OrcText> getFileFromDb() {

        List<OrcText> list = null;
        List<OrcText> listSort = new ArrayList<>();
        try {
            if (db == null)
                return null;
            list = db.findAll(OrcText.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (list == null)
            return list;
        for (int i = list.size() - 1; i >= 0; i--) {
            listSort.add(list.get(i));
        }
        list = null;
        return listSort;
    }

    private int getFialNumFromDb() {
        List<OrcText> list = null;
        try {
            list = db.selector(OrcText.class)
                    .where("resultCode", "=", "0")
                    //                .and("email", "=", "caolbmail@gmail.com")
                    //                .orderBy("regTime",true)
                    //                .limit(2) //只查询两条记录
                    //                .offset(2) //偏移两个,从第三个记录开始返回,limit配合offset达到sqlite的limit m,n的查询
                    .findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return list == null ? 0 : list.size();
    }


}
